#!/bin/sh
PWD=$(pwd)

func_clear_tags()
{
	NEED_CLEAR_FILE_NAME="tags cscope.files cscope.in.out cscope.out cscope.po.out"
	NEED_CLEAR_FILE_PATH=""

	for i in ${NEED_CLEAR_FILE_NAME}
	do
		echo "find ${PWD} ${i}......"
		TMP=$(find ${PWD} -name ${i})
		for j in ${TMP}
		do
			if [ -f ${j} ]; then
				NEED_CLEAR_FILE_PATH="${NEED_CLEAR_FILE_PATH} ${j}"
				continue
			fi
		done

		rm -rf ${NEED_CLEAR_FILE_PATH}
		echo "rm -rf ${i} success: ${NEED_CLEAR_FILE_PATH}"
		NEED_CLEAR_FILE_PATH=""
	done
}

func_touch_tags()
{
	find  ${PWD} -name "*.h" -o -name "*.c" -o -name "*.cc" > cscope.files
	cscope -bkq -i cscope.files
	ctags -R

	echo -e "--------ctags cscope SUCCESS---------"
}

func_print_usage()
{
cat <<EOF
Usage: tags.sh -a         Clean up ctags and cscope files and recreate index files.
       tags.sh -c         Clean up ctags and cscope files.
       tags.sh -t         Recreate index files.
       tags.sh -i         Set vim parameters and add the ctrlsf lightline nerdcomponent nerdtree rainbow tagbar Vundle plugin.
EOF
}

func_env_init(){
	CUR_PWD=$(pwd)
	TOOLS_FILES=".viminfo .vimrc vimrc .vim/bundle/ctrlsf.vim .vim/bundle/lightline.vim .vim/bundle/nerdcommenter .vim/bundle/nerdtree .vim/bundle/rainbow .vim/bundle/tagbar .vim/bundle/ .vim/bundle/Vundle.vim"
	CUR_USER=$(whoami)
	if [ "${CUR_USER}" != "root" ]; then
		echo "The current user is ${CUR_USER} and requires root login"
		exit
	fi

	#---------------dir check------------
	for i in ${TOOLS_FILES}
	do
		if [ ! -e ${i} ]; then
			echo "not found ${i} in ${CUR_PWD}"
			exit
		fi
	done

	#---------------download rpms---------------
	INSTALL_RPMS="ctags cscope"
	for i in ${INSTALL_RPMS}
	do
		INSTALLED=$(rpm -qa ${i})
		if [ "${INSTALLED}" == "" ]; then
			echo -e "downloading ${i}\t\t\t"
			yum install ${i} -y &> /tmp/tags_tools.log
			CHECK=$(rpm -qa ${i})
			if [ "${CHECK}" == "" ]; then
				echo -e "downloading ${i}\t\t\tFAIL"
				exit
			else
				echo -e "downloading ${i}\t\t\tSUCCESS"
			fi
		fi
	done

	#----------------clear vimrc-----------------
	RM_FILES="/root/.vimrc /root/.vim /etc/vimrc"
	for i in ${RM_FILES}
	do
		rm -rf ${i}
		echo -e "rm ${i}\t\t\tSUCCESS"
	done

	#----------------env init------------------
	cp -rf ${CUR_PWD}/vimrc /etc/vimrc
	echo -e "set /etc/vimrc\t\t\tSUCCESS"
	cp -rf ${CUR_PWD}/.vimrc /root/.vimrc
	echo -e "set /root/.vimrc\t\t\tSUCCESS"
	cp -rf ${CUR_PWD}/.vim /root/.vim
	echo -e "set /root/.vim\t\t\tSUCCESS"
	cp -rf ${CUR_PWD}/tags.sh /usr/bin/tags.sh
	echo -e "set /usr/bin/tags.sh\t\t\tSUCCESS"
}

if [ "$1" == "-a" ]; then
	func_clear_tags
	func_touch_tags
elif [ "$1" = "-c" ]; then
	func_clear_tags
elif [ "$1" = "-t" ]; then
	func_touch_tags
elif [ "$1" = "-i" ]; then
	func_env_init
else
	func_print_usage
fi
